package study.course01;

import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author linfy
 * @since 2021/11/5
 */
public class XlassLoader extends  ClassLoader{
    public static void main(String[] args) throws Exception {
        String path = "C:\\Users\\linfy\\Desktop\\JVM预\\Hello.xlass";
        XlassLoader xl = new XlassLoader();
        xl.loadXlaxx(path);
    }

    /**
     * 加载并反射执行
     * @param path
     * @throws Exception
     */
    public void loadXlaxx(String path) throws Exception {
        byte[] bytes =  Files.readAllBytes(Paths.get(path));
        byte[] dec = decode(bytes);
        Object hello = defineClass("Hello", dec, 0, dec.length).newInstance();
        Method method = hello.getClass().getMethod("hello");
        method.invoke(hello);
    }
    /**
     * 解码
     * @param bytes
     * @return
     */
    private byte[] decode(byte[] bytes){
        //255 - byte
        for (int i = 0; i < bytes.length; i++) {
            //用二进制截取
            bytes[i] = (byte) (255 -  bytes[i]& 0xff);
        }
        return bytes;
    }

}